package com.osce.basic.service;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.csce.domain.entity.basic.TabAssetInventoryConsumable;
import com.csce.domain.entity.basic.TabAssetOutOrder;
import com.osce.basic.mapper.TabAssetOutOrderMapper;
import com.osce.common.utils.DateUtils;
import com.osce.common.utils.SecurityUtils;
import com.osce.interfaces.basic.ITabAssetOutOrderService;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.Objects;

/**
 * 耗材出库Service业务层处理
 *
 * @author hdj
 * @since 2025-11-16
 */
@Service
public class TabAssetOutOrderServiceImpl extends ServiceImpl<TabAssetOutOrderMapper, TabAssetOutOrder> implements ITabAssetOutOrderService {


    /**
     * 查询耗材出库
     *
     * @param id 耗材出库主键
     * @return 耗材出库
     */
    @Override
    public TabAssetOutOrder selectTabAssetOutOrderById(String id) {
        return baseMapper.selectTabAssetOutOrderById(id);
    }

@Override
public List<TabAssetInventoryConsumable> selectTabAssetOutOrderByOrderId(String orderId) {
    // 1. 检查输入参数
    if (orderId == null || orderId.trim().isEmpty()) {
        return Collections.emptyList();
    }

    // 2. 检查查询结果
    TabAssetOutOrder tabAssetOutOrder = baseMapper.selectTabAssetOutOrderById(orderId);
    if (tabAssetOutOrder == null) {
        return Collections.emptyList();
    }

    // 3. 检查assetIdns字段
    String assetIdns = tabAssetOutOrder.getAssetIdns();
    if (assetIdns == null || assetIdns.trim().isEmpty()) {
        return Collections.emptyList();
    }

    // 4. 安全地解析JSON
    try {
        List<TabAssetInventoryConsumable> consumables = JSON.parseArray(assetIdns, TabAssetInventoryConsumable.class);
        return consumables != null ? consumables : Collections.emptyList();
    } catch (Exception e) {
        // 日志记录异常
        return Collections.emptyList();
    }
}


    /**
     * 查询耗材出库列表
     *
     * @param tabAssetOutOrder 耗材出库
     * @return 耗材出库
     */
    @Override
    public List<TabAssetOutOrder> selectTabAssetOutOrderList(TabAssetOutOrder tabAssetOutOrder) {
        return baseMapper.selectTabAssetOutOrderList(tabAssetOutOrder);
    }

    /**
     * 新增耗材出库
     *
     * @param tabAssetOutOrder 耗材出库
     * @return 结果
     */
    @Override
    public int insertTabAssetOutOrder(TabAssetOutOrder tabAssetOutOrder) {
        String orderId = generateOrderNumber();
        tabAssetOutOrder.setCreateTime(DateUtils.getNowDate());
        tabAssetOutOrder.setId(orderId);
        tabAssetOutOrder.setAudit(0);
        tabAssetOutOrder.setBusinessType(1);
        tabAssetOutOrder.setDeleted(0);
        tabAssetOutOrder.setUserId(SecurityUtils.getUserId());
        List<TabAssetInventoryConsumable> selectedConsumables = tabAssetOutOrder.getSelectedConsumables();
        if (selectedConsumables != null && !selectedConsumables.isEmpty()) {
            Long abc = selectedConsumables.stream()
            .filter(Objects::nonNull)  // Filter out null consumables
            .mapToLong(consumable -> {
                // Handle potential null number values
                Long number = consumable.getNumber();
                return number != null ? number : 0;
            })
            .sum();
            tabAssetOutOrder.setNumber(abc);
            tabAssetOutOrder.setAssetIdns(JSON.toJSONString(selectedConsumables));
        }
        return baseMapper.insertTabAssetOutOrder(tabAssetOutOrder);
    }


    /**
     * Generate order number in format OUT + YYYYMMDD + 6-digit random number
     *
     * @return Generated order number string
     */
    public String generateOrderNumber() {
        // Get current date
        java.time.LocalDate now = java.time.LocalDate.now();
        java.time.format.DateTimeFormatter formatter = java.time.format.DateTimeFormatter.ofPattern("yyyyMMdd");
        String datePart = now.format(formatter);

        // Generate 6-digit random number (100000-999999)
        java.util.Random random = new java.util.Random();
        int randomPart = 1000 + random.nextInt(9000);

        return "OUT" + datePart + randomPart;
    }


    /**
     * 修改耗材出库
     *
     * @param tabAssetOutOrder 耗材出库
     * @return 结果
     */
    @Override
    public int updateTabAssetOutOrder(TabAssetOutOrder tabAssetOutOrder) {
        return baseMapper.updateTabAssetOutOrder(tabAssetOutOrder);
    }

    /**
     * 批量删除耗材出库
     *
     * @param ids 需要删除的耗材出库主键
     * @return 结果
     */
    @Override
    public int deleteTabAssetOutOrderByIds(String[] ids) {
        return baseMapper.deleteTabAssetOutOrderByIds(ids);
    }

    /**
     * 删除耗材出库信息
     *
     * @param id 耗材出库主键
     * @return 结果
     */
    @Override
    public int deleteTabAssetOutOrderById(String id) {
        return baseMapper.deleteTabAssetOutOrderById(id);
    }
}
